package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {


    @Override
    // 根据姓名查找用户信息
    public WmUser findByName(String name) {
        WmUser one = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, name));
        return one;
    }

    @Override
    public ResponseResult login(WmUserDto dto) {
        // 检查参数
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE,"还未输入用户名获取密码");
        }
        // 通过用户名查找用户
        WmUser user = getOne(Wrappers.<WmUser>lambdaQuery()
                .eq(WmUser::getName, dto.getName())
                .eq(WmUser::getStatus, AdminConstants.PASS_AUTH));
        if (user == null){
            throw new CustomException(AppHttpCodeEnum.USER_NOT_EXIST);
        }
        // 检查密码是否正确
        String password = user.getPassword();
        String wmUserPsw = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes());
        if (!password.equals(wmUserPsw)){
            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 颁发凭证
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
        // 新建map给结果赋值
        Map map = new HashMap<>();
        user.setPassword("");
        user.setSalt("");
        map.put("user",user);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}
